﻿var currUser;

$(document).ready(function () {
	getNewUser();

	getCurrUser().Type = getUrlParameter('userType');

	$("#imgCostumer, #imgOwner").each(function () {
		$(this).hide();
	});

	if (getCurrUser().Type == 'C') {
		$("#imgCostumer").show();
	} else {
		$("#imgOwner").show();
	}

	$("span[controlToValidate]").hide();

	$("#txtNombre").val(getCurrUser().Name);
	$("#txtUserName").val(getCurrUser().UserName);
	$("#txtMail").val(getCurrUser().Mail);
	$("#txtAddress").val(getCurrUser().Adress);
	$("#txtTelephone").val(getCurrUser().Telephone);
	$("#txtCellphone").val(getCurrUser().Cellphone);
	$("#txtPassword").val(getCurrUser().Password);

	$("#txtNombre").change(function () {
		getCurrUser().Name = $(this).val();
	});
	$("#txtMail").change(function () {
		getCurrUser().Mail = $(this).val();
	});
	$("#txtAddress").change(function () {
		getCurrUser().Adress = $(this).val();
	});
	$("#txtTelephone").change(function () {
		getCurrUser().Telephone = $(this).val();
	});
	$("#txtCellphone").change(function () {
		getCurrUser().Cellphone = $(this).val();
	});
	$("#txtUserName").change(function () {
		getCurrUser().UserName = $(this).val();
	});
	$("#txtPassword").change(function () {
		getCurrUser().Password = $(this).val();
	});

	$("#btnSave").click(function () {
		if (validateForm('#divInsertUser')) {
			alert('Registro guardado');
			insertUser();
		}
	});
});

function getCurrUser() {
	return currUser;
}

function getNewUser() {
	$.ajax({
		dataType: "json",
		async: false,
		url: "getNewUser",
		success: function (user) {
			currUser = user;
		},
		error: function (xhr, ajaxOptions, thrownError) {
			document.write(xhr.responseText);
		}
	});
}

function insertUser() {
	$.ajax({
		type: "POST",
		async: false,
		url: "/User/insertUser",
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify(getCurrUser()),
		error: function (xhr, ajaxOptions, thrownError) {
			document.write(xhr.responseText);
		}
	});
	window.location.href="/Login/Index";
}

//function validateForm() {
//	var valid = true;

//	$("span[controlToValidate]").each(function () {
//		var control = $("#" + $(this).attr('controlToValidate'));

//		if (valid) {
//			valid = (control.val().length != 0);
//		}

//		$(this).toggle(control.val().length == 0);
//	});

//	return valid;
//}